//
//  QCHomeViewController.m
//  QCAppProject
//
//  Created by yjl on 2021/8/16.
//

#import "QCHomeViewController.h"
#import "QCGradientLayerUtil.h"
#import "HomeTopView.h"
#import "HomeTableViewCell.h"
#import "HomeTableHeadView.h"
#import "QCLoginViewController.h"
#import "QCNetworkManager.h"
#import "QCInformationModel.h"
#import "QCConsultViewController.h"
#import "QCInformationViewController.h"
#import "QCCooperationViewController.h"
#import "QCWebViewController.h"
#import "YFHUtil.h"
#import "QCInformationDetailVC.h"
#import "FDDPrivacyView.h"
#import "QCUserProtocolViewController.h"
#import "QCPrivacyPolicyViewController.h"
#import "YFHRefresh.h"
#import <MJRefresh/MJRefresh.h>
#import "NSString+Ext.h"
#import "FDDKeyChain.h"

const CGFloat topHeight = 175.0;

@interface QCHomeViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) HomeTopView *topView;
@property (nonatomic, strong) UITableView *homeTableView;
@property (nonatomic, strong) HomeTableHeadView *headView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) FDDPrivacyView *privacyView;
@property (nonatomic, strong) YFHRefresh *refreah;

@end

@implementation QCHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self loadData];
    [self configRefreshTable];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)initUI {
    [self.view addSubview:self.topView];
    [self.view addSubview:self.homeTableView];
    [self.homeTableView reloadData];
    [self checkPrivacyView];
}

- (void)configRefreshTable {
    self.refreah = [[YFHRefresh alloc] init];
    WS(weakSelf)
    [self.refreah normalModelRefresh:self.homeTableView refreshType:(RefreshTypeDropDown) firstRefresh:NO timeLabHidden:NO stateLabHidden:NO dropDownBlock:^{
        if ([weakSelf.homeTableView.mj_header isRefreshing]) {
            [weakSelf.homeTableView.mj_header endRefreshing];
        }
        [self loadData];
    } upDropBlock:nil];
}

//加载列表数据
- (void)loadData {
    WS(weakSelf)
    [QCNetworkManager getRequestWithURL:[QCSingleton instance].URL.noticeUrl parameters:nil Progress:nil success:^(id  _Nonnull responseObject) {
        QCLog(@"=====>>%@",responseObject);
        weakSelf.dataArray = [QCInformationModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [weakSelf.homeTableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        QCLog(@"=====>>%@",error.description);
    }];
}

//查询地址接口
- (void)loadQueryLinkUrlData:(QCQueryLinkType)queryLinkType {
    WS(weakSelf)
    NSString *registrationID = [[NSUserDefaults standardUserDefaults] objectForKey:kJpushRegistrationID];
    NSString *link = @"";
    if (queryLinkType == QCQueryLinkFefu) {
        link = [QCSingleton instance].URL.queryKefuUrl;
    } else {
        link = [NSString stringWithFormat:@"%@?mchid=%@",[QCSingleton instance].URL.queryLinkUrl,registrationID];
    }
    [QCNetworkManager getRequestWithURL:link parameters:nil Progress:nil success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = responseObject;
            if ([dict.allKeys containsObject:@"data"]) {
                NSDictionary *dict = responseObject[@"data"];
                if (dict && [dict.allKeys containsObject:@"link"]) {
                    NSString *link = dict[@"link"];
                    QCWebViewController *webVC = [QCWebViewController new];
                    webVC.url = link;
                    webVC.queryLinkType = queryLinkType;
                    [weakSelf.navigationController pushViewController:webVC animated:YES];
                }
            }
        }
    QCLog(@"=====>>%@",responseObject);
    } failure:^(NSError *error) {
        QCLog(@"=====>>%@",error.description);
    }];
}

- (void)pushToVC:(NSInteger)index {
    QCLog(@"%@",@(index));
    if (index == 1) {
        if ([YFHUtil isBlankString:[QCSingleton instance].account] ) {
            QCLoginViewController *login = [[QCLoginViewController alloc] init];
            login.modalPresentationStyle = UIModalPresentationFullScreen;
            login.loginSuccessBlock = ^{
                QCConsultViewController *consultViewController = [[QCConsultViewController alloc] init];
                [self.navigationController pushViewController:consultViewController animated:YES];
            };
            QCNavigationViewController *nav = [[QCNavigationViewController alloc] initWithRootViewController:login];
            [self presentViewController:nav animated:YES completion:nil];
            return;
        }
        QCConsultViewController *consultViewController = [[QCConsultViewController alloc] init];
        [self.navigationController pushViewController:consultViewController animated:YES];
    } else if (index == 2) {
        QCInformationViewController *informationViewController = [[QCInformationViewController alloc] init];
        [self.navigationController pushViewController:informationViewController animated:YES];
    } else if (index == 3) {
        [self loadQueryLinkUrlData:QCQueryLinkFefu];
    } else {
        [self loadQueryLinkUrlData:QCQueryLinkDefault];
    }
    
}

#pragma mark -- 校验隐私政策是否同意
- (void)checkPrivacyView {
    BOOL isArrow =  [[NSUserDefaults standardUserDefaults] boolForKey:@"isArrowPrivacy"];
    if (isArrow) {
        //已经同意了隐私政策
        [self.privacyView removeFromSuperview];
        return;
    } else {
        //隐私政策更新提示界面
        [[UIApplication sharedApplication].keyWindow addSubview:self.privacyView];
    }
}

#pragma mark - 隐私政策
//同意
- (void)agreeBtnPressed {
    //同意隐私政策；
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isArrowPrivacy"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.privacyView removeFromSuperview];}

- (void)notAgreeBtnPressed {
    [QCProgressHUD showHUDWithMessage:@"同意后才可继续使用奇成科技服务" autoHide:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeTableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell configCellData:self.dataArray[indexPath.row]];
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    QCInformationDetailVC *detailVC = [QCInformationDetailVC new];
    QCInformationModel *model = self.dataArray[indexPath.row];
    detailVC.detailLink = model.htmltxt;
    detailVC.mainTitle = model.title;
    detailVC.subTitle = model.createDateStr;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (HomeTopView *)topView {
    if (!_topView) {
        _topView = [[HomeTopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,topHeight)];
        WS(weakSelf)
        _topView.itemClickedBlock = ^(NSInteger index) {
            [weakSelf pushToVC:index];
        };
    }
    return _topView;
}

- (HomeTableHeadView *)headView {
    if (!_headView) {
        _headView = [[HomeTableHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    }
    return _headView;
}

- (UITableView *)homeTableView {
    if (!_homeTableView) {
        _homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topHeight, SCREEN_WIDTH, SCREEN_HEIGHT - topHeight - kTabBarHeight) style:(UITableViewStylePlain)];
        _homeTableView.backgroundColor = [UIColor clearColor];
        _homeTableView.delegate = self;
        _homeTableView.dataSource = self;
        _homeTableView.tableHeaderView = self.headView;
        _homeTableView.estimatedRowHeight = 100;
        _homeTableView.estimatedSectionHeaderHeight = 0;
        _homeTableView.estimatedSectionFooterHeight = 0;
        _homeTableView.rowHeight = UITableViewAutomaticDimension;
        _homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_homeTableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"HomeTableViewCell"];
    }
    return _homeTableView;
}

- (NSArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

-(FDDPrivacyView *)privacyView{
    
    if (!_privacyView) {
        _privacyView = [[FDDPrivacyView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        
        [_privacyView.agreeBtn addTarget:self action:@selector(agreeBtnPressed) forControlEvents:UIControlEventTouchUpInside];
        [_privacyView.notAgreeBtn addTarget:self action:@selector(notAgreeBtnPressed) forControlEvents:UIControlEventTouchUpInside];
        
        WS(weakSelf);
        _privacyView.privacyBtnBlock = ^(NSString * _Nonnull URL) {
             weakSelf.privacyView.hidden = YES;
             if ([URL isEqualToString:@"useagreement"]) {//用户协议
                 QCUserProtocolViewController *userProtocolVC = [[QCUserProtocolViewController alloc]init];
                 userProtocolVC.isProtocolJump = ^{
                     weakSelf.privacyView.hidden = NO;
                 };
                [weakSelf.navigationController pushViewController:userProtocolVC animated:YES];
             }else{//隐私政策
                 QCPrivacyPolicyViewController *privacyVC = [[QCPrivacyPolicyViewController alloc]init];
                 privacyVC.privacyPolicyJump = ^{
                     weakSelf.privacyView.hidden = NO;
                 };
                 [weakSelf.navigationController pushViewController:privacyVC animated:YES];
             }
        };
    }
    return _privacyView;
}

@end
